import 'dart:async';
import 'dart:io';

import 'package:acaleph/Utils/route_util.dart';
import 'package:acaleph/common/constant.dart';
import 'package:acaleph/model/base_model.dart';
import 'package:acaleph/model/test_detail_model.dart';
import 'package:acaleph/model/test_list_model.dart';
import 'package:acaleph/mvp/presenter/list_presenter.dart';
import 'package:acaleph/mvp/presenter/list_presenter_impl.dart';
import 'package:acaleph/widget/common_divider.dart';
import 'package:acaleph/widget/common_snakeBar.dart';
import 'package:flutter/material.dart';
import 'package:transparent_image/transparent_image.dart';

class ListPage extends StatefulWidget {

  ListPage({Key key}) : super(key: key);

  @override
  _ListPageState createState() {
    _ListPageState view = new _ListPageState();
    ListPresenter presenter = new ListPresenterImpl(view);
    presenter.init();
    return view;
  }
}

enum AppBarBehavior { normal, pinned, floating, snapping }

class _ListPageState extends State<ListPage> implements TestListView {
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
      new GlobalKey<RefreshIndicatorState>();

  ScrollController _scrollController;

  ListPresenter _ListPresenter;

  final double _appBarHeight = 256.0;

  String _title = Constant.themeTitle;

  AppBarBehavior _appBarBehavior = AppBarBehavior.pinned;

  String _barBg = Constant.defBg;

  List<TestListModel> _normalDatas = [];

  bool _isSlideUp = false;

  List<Widget> _widgets = [];


  void _scrollListener() {
    //滑到最底部刷新
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {

      _loadData();
    }
  }


  Future<Null> _refreshData() {
    _isSlideUp = false;

    final Completer<Null> completer = new Completer<Null>();

    _ListPresenter.loadList(0);

    completer.complete(null);

    return completer.future;
  }


  Future<Null> _loadData() {
    _isSlideUp = true;

    final Completer<Null> completer = new Completer<Null>();

    _ListPresenter.loadList(_normalDatas.length);

    setState(() {});

    completer.complete(null);

    return completer.future;
  }

  @override
  void initState() {
    super.initState();
    _scrollController = new ScrollController()..addListener(_scrollListener);
    _refreshData();
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.removeListener(_scrollListener);
  }

  Widget _buildList(BuildContext context) {
    var content = new CustomScrollView(
      //没有铺满也可以滑动
      physics: AlwaysScrollableScrollPhysics(),
      controller: _scrollController,
      slivers: <Widget>[
        new SliverAppBar(
          expandedHeight: _appBarHeight,
          pinned: _appBarBehavior == AppBarBehavior.pinned,
          floating: _appBarBehavior == AppBarBehavior.floating ||
              _appBarBehavior == AppBarBehavior.snapping,
          snap: _appBarBehavior == AppBarBehavior.snapping,
          flexibleSpace: new FlexibleSpaceBar(
            //标题
            title: Text('$_title'),
            centerTitle: true,
            //背景图
            background: new FadeInImage.memoryNetwork(
                placeholder: kTransparentImage,
                image: _barBg,
                fit: BoxFit.fitHeight),
          ),
        ),
        new SliverList(
          delegate: new SliverChildListDelegate(
              new List<Widget>.generate(_normalDatas.length, (int i) {
            return _buildNewItem(_normalDatas[i]);
          })),
        ),
        new SliverList(
          delegate: new SliverChildListDelegate(
              new List<Widget>.generate(1, (int i) {
                return new Center(
                  child: new Container(
                    margin: const EdgeInsets.only(top: 8.0),
                    width: 32.0,
                    height: 32.0,
                    child: const CircularProgressIndicator(),
                  ),
                );
              })),
        ),

      ],
    );

    var _refreshIndicator = new RefreshIndicator(
      key: _refreshIndicatorKey,
      onRefresh: _refreshData,
      child: content,
    );

    return _refreshIndicator;
  }

  Widget _buildNewItem(TestListModel item) {
    Widget widget;
//    多个列表可在这里分支
//    switch (item.itemType) {
//      case ThemeListStoriesModel.itemTypeEditor:
//        widget = _buildEditor();
//        break;
//      case ThemeListStoriesModel.itemTypeNormal:
//        widget = _buildNormalItem(item);
//        break;
//    }
    widget = _buildNormalItem(item);
    return widget;
  }

  Widget _buildNormalItem(TestListModel item) {
    final String images = _barBg;
    final String title = item.title;
    final int id = item.id;
    bool hasImage = (null != images && images.isNotEmpty);

    if (hasImage) {
      return new InkWell(
          onTap: () {
            RouteUtil.route2Detail(context, '$id');
          },
          child: new Padding(
              padding: const EdgeInsets.only(left: 12.0, right: 12.0),
              child: new SizedBox(
                height: Constant.normalItemHeight,
                child: new Column(
                  children: <Widget>[
                    new Row(
                      children: <Widget>[
                        new Expanded(
                          child: new Text(
                            title,
                            style: new TextStyle(
                                fontSize: 16.0, fontWeight: FontWeight.w300),
                          ),
                        ),
                        new Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: new SizedBox(
                            height: 80.0,
                            width: 80.0,
                            child: new Image.network(images),
                          ),
                        )
                      ],
                    ),
                    new Expanded(
                      child: new Align(
                        alignment: Alignment.bottomCenter,
                        child: CommonDivider.buildDivider(),
                      ),
                    ),
                  ],
                ),
              )));
    } else {
      return new InkWell(
          onTap: () {
            RouteUtil.route2Detail(context, '$id');
          },
          child: new Padding(
              padding: const EdgeInsets.only(left: 12.0, right: 12.0),
              child: new SizedBox(
                height: Constant.normalItemHeight,
                child: new Column(
                  children: <Widget>[
                    new Row(
                      children: <Widget>[
                        new Expanded(
                          child: new SizedBox(
                            height: Constant.normalItemHeight,
                            child: new Align(
                              alignment: Alignment.centerLeft,
                              child: new Text(
                                title,
                                style: new TextStyle(
                                    fontSize: 16.0,
                                    fontWeight: FontWeight.w300),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    new Expanded(
                      child: new Align(
                        alignment: Alignment.bottomCenter,
                        child: CommonDivider.buildDivider(),
                      ),
                    ),
                  ],
                ),
              )));
    }
  }

  _refreshItems() {
    for (TestListModel model in _normalDatas) {
      _widgets.add(_buildNewItem(model));
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
//      key: _scaffoldKey,
      backgroundColor: Colors.white,

      body: _buildList(context),
    );
  }

  @override
  void onLoadListFail() {
    // TODO: implement onLoadListFail
  }

  @override
  void onLoadListSuc(BaseModel<List<TestListModel>> model) {
    if (!mounted) return; //异步处理，防止报错

    if (model.code != HttpStatus.OK) {
      CommonSnakeBar.buildSnakeBar(context, model.errorMsg);
      return;
    }

    if (_isSlideUp) {
      List<TestListModel> normalList = model.data;
      _normalDatas.addAll(normalList);
    } else {
      List<TestListModel> normalList = model.data;

      _normalDatas.clear();
      _normalDatas = normalList;

    }

    _refreshItems();
  }

  @override
  setPresenter(ListPresenter presenter) {
    _ListPresenter = presenter;
  }
}
